<script setup lang="ts">
import { reactive, ref, watch, onMounted } from 'vue'
import { uploadFile } from '@/utils/uploader'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import '@vueup/vue-quill/dist/vue-quill.core.css'
import '@vueup/vue-quill/dist/vue-quill.bubble.css'
import 'quill-image-uploader/dist/quill.imageUploader.min.css'
import Quill from 'quill'

import ImageUploader from 'quill-image-uploader'
import BlotFormatter from 'quill-blot-formatter'

import Compressor from 'compressorjs'

const props = withDefaults(
  defineProps<{
    modelValue: any // 双向绑定值
  }>(),
  {
    modelValue: '' // 双向绑定值
  }
)
const emit = defineEmits<{
  (e: 'update:modelValue', val: any): void
}>()
const content = ref<string>('')
const quillRef = ref<any>(null)

Quill.register('modules/imageUploader', ImageUploader)
Quill.register('modules/blotFormatter', BlotFormatter)

const Size = Quill.import('attributors/style/size')
Size.whitelist = ['12px', '14px', '16px', '18px', '20px', '32px']
Quill.register(Size, true)

// 自定义字体类型
const Font = Quill.import('attributors/style/font')
Font.whitelist = ['Microsoft-YaHei', 'KaiTi', 'FangSong', '宋体', '黑体']
Quill.register(Font, true)

//富文本配置项，将模块功能一起写入到配置项内，也可以单独配置Modules
const myOptions = reactive({
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'], // toggled buttons
      ['blockquote', 'code-block'],
      ['link', 'image', 'video'],
      [{ list: 'ordered' }, { list: 'bullet' }],
      [{ indent: '-1' }, { indent: '+1' }],
      [{ header: [1, 2, 3, 4, 5, 6, false] }],
      [{ color: [] }, { background: [] }], // dropdown with defaults from theme
      [{ size: Size.whitelist }],
      [{ font: Font.whitelist }] // 字体种类
    ],
    // 上传图片
    imageUploader: {
      upload: async (file: any) => {
        try {
          const compressedFile: any = await compressImage(file) // 压缩图片
          console.log(file)
          return new Promise((resolve, reject) => {
            uploadFile({ file: compressedFile })
              .then((res: any) => {
                resolve(res.url)
              })
              .catch((err) => {
                reject('Upload failed')
                console.error('Error:', err)
              })
          })
        } catch (error) {
          console.error('压缩和上传图像时出错:', error)
        }
      }
    },
    // 图片缩放
    blotFormatter: {}
  },
  placeholder: '请输入内容...'
})

// 图片压缩
const compressImage = (file: any) => {
  return new Promise((resolve, reject) => {
    new Compressor(file, {
      quality: 0.6, // 设置压缩质量
      maxWidth: 400, // 设置图片最大宽度
      maxHeight: 400, // 设置图片最大高度
      success(result) {
        resolve(result)
      },
      error(error) {
        reject(error)
      }
    })
  })
}

const setValue = () => {
  //用于设置双向绑定值
  console.log(quillRef.value)
  const text = quillRef.value.getHTML()
  emit('update:modelValue', text)
}

watch(
  () => props.modelValue,
  (val: any) => {
    if (val) {
      content.value = val //用于监听绑定值进行数据回填
    } else {
      // quillRef.value.setContents('') //可用于弹窗使用富文本框关闭弹窗清除值
    }
  },
  {
    immediate: true
  }
)

onMounted(() => {
  document.querySelector('.ql-tooltip input').setAttribute('data-video', '资源地址')
})
</script>
<template>
  <QuillEditor ref="quillRef" v-model:content="content" :options="myOptions" contentType="html" @update:content="setValue()" />
</template>
<style lang="scss">
.ql-container {
  //通过calc函数动态设置富文本高度，前提父容器有具体高度
  width: 100%;
  height: 250px;
}

.ql-toolbar {
  width: 100%;
}

// .ql-snow.ql-toolbar .ql-picker-label.ql-active {
//   background-color: #fff;
//   color: #4b5563;
// }
.ql-snow .ql-tooltip[data-mode='video']::before {
  content: '视频:';
}

.ql-snow .ql-tooltip[data-mode='link']::before {
  content: '链接:';
}

.ql-snow .ql-tooltip.ql-editing a.ql-action::after {
  content: '保存';
}

.ql-size .ql-picker-label[data-value='12px']::before,
.ql-size .ql-picker-item[data-value='12px']::before {
  content: '12px' !important;
}

.ql-size .ql-picker-label[data-value='14px']::before,
.ql-size .ql-picker-item[data-value='14px']::before {
  content: '14px' !important;
}

.ql-size .ql-picker-label[data-value='16px']::before,
.ql-size .ql-picker-item[data-value='16px']::before {
  content: '16px' !important;
}

.ql-size .ql-picker-label[data-value='18px']::before,
.ql-size .ql-picker-item[data-value='18px']::before {
  content: '18px' !important;
}

.ql-size .ql-picker-label[data-value='20px']::before,
.ql-size .ql-picker-item[data-value='20px']::before {
  content: '20px' !important;
}

.ql-size .ql-picker-label[data-value='24px']::before,
.ql-size .ql-picker-item[data-value='24px']::before {
  content: '24px' !important;
}

.ql-size .ql-picker-label[data-value='28px']::before,
.ql-size .ql-picker-item[data-value='28px']::before {
  content: '28px' !important;
}

.ql-size .ql-picker-label[data-value='32px']::before,
.ql-size .ql-picker-item[data-value='32px']::before {
  content: '32px' !important;
}

.ql-size .ql-picker-label[data-value='36px']::before,
.ql-size .ql-picker-item[data-value='36px']::before {
  content: '36px' !important;
}

.ql-font .ql-picker-label[data-value='Microsoft-YaHei']::before,
.ql-font .ql-picker-item[data-value='Microsoft-YaHei']::before {
  content: '微软雅黑' !important;
}
.ql-font .ql-picker-label[data-value='KaiTi']::before,
.ql-font .ql-picker-item[data-value='KaiTi']::before {
  content: '楷体' !important;
}

.ql-font .ql-picker-label[data-value='FangSong']::before,
.ql-font .ql-picker-item[data-value='FangSong']::before {
  content: '仿宋' !important;
}

.ql-font .ql-picker-label[data-value='宋体']::before,
.ql-font .ql-picker-item[data-value='宋体']::before {
  content: '宋体' !important;
}

.ql-font .ql-picker-label[data-value='黑体']::before,
.ql-font .ql-picker-item[data-value='黑体']::before {
  content: '黑体' !important;
}

.ql-header .ql-picker-label[data-value='1']::before,
.ql-header .ql-picker-item[data-value='1']::before {
  content: '1号' !important;
}

.ql-header .ql-picker-label[data-value='2']::before,
.ql-header .ql-picker-item[data-value='2']::before {
  content: '2号' !important;
}

.ql-header .ql-picker-label[data-value='3']::before,
.ql-header .ql-picker-item[data-value='3']::before {
  content: '3号' !important;
}

.ql-header .ql-picker-label[data-value='4']::before,
.ql-header .ql-picker-item[data-value='4']::before {
  content: '4号' !important;
}

.ql-header .ql-picker-label[data-value='5']::before,
.ql-header .ql-picker-item[data-value='5']::before {
  content: '5号' !important;
}

.ql-header .ql-picker-label[data-value='6']::before,
.ql-header .ql-picker-item[data-value='6']::before {
  content: '6号' !important;
}

.ql-header .ql-picker-label::before,
.ql-header .ql-picker-item::before {
  content: '普通字号' !important;
}
</style>
